﻿using BBICMS.Model;
using BBICMS.Model.ViewModel.Front;
using BBICMS.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BBICMS.Application.ViewModels;
using BBICMS.Model.Works;
using PagedList;

namespace BBICMS.WebUI.Controllers
{
    public class WorkController : BaseController
    {
     
        //
        // GET: /Work/

        public ActionResult Index(int? page,int? sid,int? cid)
        {
            var pageNumber = page ?? 1;
            

            var works = new List<Work>();


            if (cid != null)
            {
                works = _unit.WorkTypes.GetFirstOrDefault((m => m.Active && m.Id == cid), (m => m.Works)).Works.OrderByDescending(m => m.AddedDate).ToList();
                if (sid != null)
                    works = works.Where(m => m.SolutionId == sid).ToList();

            }
            else
            {
                if (sid != null)
                    works =
                        _unit.Works.GetAll()
                            .Where(m => m.Active && m.SolutionId == sid)
                            .OrderByDescending(m => m.AddedDate)
                            .ToList();
                else
                {
                    works = _unit.Works.GetAll()
                            .Where(m => m.Active)
                            .OrderByDescending(m => m.AddedDate)
                            .ToList();
                }
            }
               
            
            var vm = new WorkListVM
            {
                SolutionId =  sid,
                TypeId = cid,
                PageIndex = pageNumber,

                Solutions = _unit.Solutions.GetAll().Where(m=>m.Active).OrderByDescending(m=>m.Importance),

                Types = (from lc in _unit.WorkTypes.GetAll()
                    orderby lc.Importance descending
                    select lc).ToList(),
                Works = works.ToList().ToPagedList(pageNumber, 12)
            };


            return View(vm);
        }

        // GET: /Work/Detail
        public ActionResult Detail(int id)
        {
            Work vWork = _unit.Works.GetById(id);
            vWork.ViewCount += 1;
            _unit.Works.Update(vWork);
            _unit.SaveChanges();

            return View(vWork);
        }

    }
}
